package com.yami.shop.mystery.platform.task;


import cn.hutool.core.util.ObjectUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.mystery.common.dto.ActivityPresellDto;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.ActivityProd;
import com.yami.shop.mystery.common.model.ActivityRule;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.ActivityProdService;
import com.yami.shop.mystery.common.service.ActivityRuleService;
import com.yami.shop.service.ProductService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class ActivityAutoReplenishTask {

    @Autowired
    private ActivityPresellService presellService;

    @Autowired
    private ActivityRuleService activityRuleService;

    @Autowired
    private ActivityProdService activityProdService;

    @Autowired
    private ProductService productService;

    @XxlJob("activityAutoReplenishTask")
    public void activityAutoReplenishTask() {
        log.info("活动定时补货任务开始");
        List<ActivityPresellDto> autoReplenishList = presellService.getAutoReplenishList();
        if (autoReplenishList.isEmpty()) {
            log.info("无待补货的活动");
            return;
        }
        for (ActivityPresellDto activityPresellDto : autoReplenishList) {
            ActivityRule activityRule = activityRuleService.getById(Long.valueOf(activityPresellDto.getActivityRule()));
            if (ObjectUtil.isNull(activityRule)) {
                log.error("活动{}配置的补货规则未找到,跳过", activityPresellDto.getActivityName());
                continue;
            }
            log.info("获取活动配置规则成功");
            Integer addStocks = 0;
            List<ActivityProd> activityProds = activityProdService.listByActivityId(activityPresellDto.getId());
            if (!activityProds.isEmpty()) {
                for (ActivityProd activityProd : activityProds) {
                    log.info("活动商品{}，剩余库存{}，已补货库存{},配置文件中补货阈值{}，配置文件中最大补货库存{}",activityProd.getProdId(),activityProd.getProdTotalStocks(),activityProd.getAlreadyReplenishmentQuantity(),activityRule.getReplenishmentThreshold(),activityRule.getMaxReplenishmentQuantity());
                    // 本次补货规则生效，判断商品库存是否还剩余
                    if (ObjectUtil.isNotNull(activityProd.getProdTotalStocks()) && activityProd.getProdTotalStocks() <= activityRule.getReplenishmentThreshold() && activityProd.getAlreadyReplenishmentQuantity() < activityRule.getMaxReplenishmentQuantity()) {
                        log.info("本次补货规则生效，判断商品库存是否还剩余");
                        // 查询该商品参与活动的有效库存数
                        Integer allStocks = presellService.selectStocksByProdId(activityProd.getProdId());
                        // 判断该商品是否还有库存机库存是否还满足本次活动预扣减
                        Product productInfo = productService.getProductInfo(activityProd.getProdId());
                        Integer stocks = productInfo.getTotalStocks() - allStocks;
                        if (productInfo.getTotalStocks() > 0 && stocks > 0 && stocks > activityRule.getReplenishmentQuantity()) {
                            Integer prodTotalStocks = activityProd.getProdTotalStocks() + activityRule.getReplenishmentQuantity();
                            activityProd.setProdTotalStocks(prodTotalStocks);
                            activityProd.setProdOriginStocks(activityProd.getProdOriginStocks() + activityRule.getReplenishmentQuantity());
                            activityProd.setAlreadyReplenishmentQuantity(activityProd.getAlreadyReplenishmentQuantity() + activityRule.getReplenishmentQuantity());
                            activityProdService.updateById(activityProd);
                            addStocks += activityRule.getReplenishmentQuantity();
                            // 移除缓存数据
                            activityProdService.removeActivitySkuCache(activityPresellDto.getId(), activityProd.getProdId());

                            String key = "ACTIVITY_SKU_STOCKS_" + activityPresellDto.getId()+"_"+activityProd.getProdId();
                            RedisUtil.setLongValue(key, Long.valueOf(prodTotalStocks), -1);
                        } else {
                            log.error("该商品剩余库存为：" + stocks + ",本次补货库存为：" + activityRule.getReplenishmentQuantity() + ",已补货数量为" + activityProd.getAlreadyReplenishmentQuantity() + "商品库存不足！");
                        }
                    } else {
                        log.error("活动库存不符合补货规则");
                    }
                }
            }

            if (addStocks > 0) {
                ActivityPresell activityPresell = new ActivityPresell();
                activityPresell.setId(activityPresellDto.getId());
                activityPresell.setTotalStocks(activityPresellDto.getTotalStocks() + addStocks);
                activityPresell.setOriginStocks(activityPresellDto.getOriginStocks() + addStocks);
                presellService.updateById(activityPresell);
            }
        }
        log.info("活动定时补货任务结束");
    }
}
